class Solution {
    public int numIslands(char[][] grid) {
        int h = grid.length, w = grid[0].length;
        boolean[][] visited = new boolean[h][w];
        int res = 0;

        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                if (!visited[i][j] && grid[i][j] == '1'){
                    findIsland(grid, i, j, visited);
                    res++;
                }
            }
        }
        return res;
    }

    private void findIsland(char[][] grid, int i, int j, boolean[][] visited){
        visited[i][j] = true;
        if (grid[i][j] == '0') {
            return;
        }

        int[][] directions = {{1,0},{-1,0},{0,1},{0,-1}};
        for (int[] dir : directions) {
            int newi = i+dir[0], newj = j+dir[1];
            if (newi >= 0 && newi < grid.length && newj >= 0 && newj < grid[0].length) {
                if (!visited[newi][newj]){
                    findIsland(grid, newi, newj, visited);
                }
            }
        }
    }

    public int numIslands1(char[][] grid) {
        int h = grid.length, w = grid[0].length;
        int res = 0;
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                if (grid[i][j] == '1'){
                    dfs(grid, i, j);
                    res++;
                }
            }
        }
        return res;
    }

    private void dfs(char[][] grid, int i, int j) {
        if (!inArea(grid, i, j)){
            return;
        }

        if (grid[i][j] != '1') {
            return;
        }

        grid[i][j] = 2;

        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }

    private boolean inArea(char[][] grid, int i, int j) {
        return 0 <= i && i < grid.length && 0 <= j && j < grid[0].length;
    }
}